<template>
  <div>
    <div>
      <van-sticky>
        <el-card shadow="nover" class="mobile-card-search">
          <el-row :gutter="20">
            <el-col :span="20">
              <el-input
                placeholder="请输入提交人"
                prefix-icon="el-icon-search"
                v-model="queryParams.createBy"
                @keyup.enter.native="handleQuery"
              ></el-input>
            </el-col>
            <el-col :span="4">
              <i
                :style="{ color: colorFlag ? '#1890ff' : '' }"
                class="el-icon-s-operation search-icon"
                @click="showPicker = true"
              ></i>

              <!-- 搜索弹窗 -->
              <van-popup
                v-model="showPicker"
                position="bottom"
                round
                style="height: 80%"
                close-icon="close"
                closeable
                @close="popupClose"
                class="modal-content"
              >
                <h3 style="text-align: center">筛选</h3>
                <van-form class="modal-body" ref="queryForm">
                  <searchable-picker
                    :default-index="4"
                    v-model="queryParams.taskType"
                    :columns="dict.type.task_type"
                    valueKey="value"
                    labelKey="label"
                    label="工单类型选择"
                    placeholder="点击工单类型"
                  />
                  <searchable-picker
                    v-model="queryParams.userId"
                    :columns="userList"
                    valueKey="userId"
                    labelKey="userName"
                    label="负责人"
                    placeholder="点击选择负责人"
                  />
                  <searchable-picker
                    v-model="queryParams.customerId"
                    :columns="customerList"
                    valueKey="customerId"
                    labelKey="customerName"
                    label="客户"
                    placeholder="点击选择客户"
                  />
                  <searchable-picker
                    v-model="queryParams.orderId"
                    :columns="orderListAll"
                    valueKey="orderId"
                    labelKey="orderName"
                    label="商机"
                    placeholder="点击选择商机"
                  />
                  <van-field
                    v-model="queryParams.createBy"
                    label="提交人"
                    placeholder="请输入提交人"
                  />
                </van-form>
                <div style="" class="modal-footer">
                  <van-button
                    type="default"
                    style="width: 40%; border-radius: 10px"
                    @click="resetQuery"
                    >重置</van-button
                  >
                  <van-button
                    type="info"
                    style="width: 40%; border-radius: 10px"
                    @click="handleQuery"
                    >查询</van-button
                  >
                </div>
              </van-popup>
              <!-- 搜索弹窗 -->
            </el-col>
          </el-row>
        </el-card>
      </van-sticky>
    </div>
    <div class="mobile-container">
      <van-list
        v-model="loading"
        :finished="finished"
        @load="getList"
        finished-text="没有更多了...."
      >
        <div v-if="taskList.length > 0">
          <el-card
            class="mobile-card"
            shadow="hover"
            v-for="task in taskList"
            :key="task.weeklyId"
          >
            <div slot="header">
              <span class="mobile-card-titel"
                >{{ task.createBy }} 提交的 {{ task.year }} 工单</span
              >
              <van-popover
                placement="bottom-end"
                style="float: right"
                v-model="task.flag"
                trigger="click"
                :actions="task.actions"
                @select="onSelect($event, task.id)"
                @closed="
                  () => {
                    task.flag = false;
                  }
                "
              >
                <template #reference>
                  <i
                    class="el-icon-more"
                    @click.stop="task.flag = true"
                  ></i>
                </template>
              </van-popover>
            </div>
            <div style="color: gray; font-size: small">负责人：</div>
            <div style="margin: 10px 0; font-size: medium">
              {{ task.userName }}
            </div>
            <div style="color: gray; font-size: small">工单类型：</div>
            <div style="margin: 10px 0; font-size: medium">
              <dict-tag :options="dict.type.task_type" :value="task.taskType"/>
            </div>
            <div style="color: gray; font-size: small">关联商机：</div>
            <div style="margin: 10px 0; font-size: medium">
              {{ task.orderName }}
            </div>
            <div style="color: gray; font-size: small">关联客户：</div>
            <div style="margin: 10px 0; font-size: medium">
              {{ task.customerName }}
            </div>
            <div style="color: gray; font-size: small">实施开始时间：</div>
            <div style="margin: 10px 0; font-size: medium">
              {{ task.startTime }}
            </div>
            <div style="color: gray; font-size: small">实施结束时间：</div>
            <div style="margin: 10px 0; font-size: medium">
              {{ task.endTime }}
            </div>
            <div style="color: gray; font-size: small">实际天数：</div>
            <div style="margin: 10px 0; font-size: medium">
              {{ task.actualDay }}
            </div>
            <div style="color: gray; font-size: small">紧急程度：</div>
            <div style="margin: 10px 0; font-size: medium">
              <dict-tag :options="dict.type.task_level" :value="task.taskLevel"/>
            </div>
            <div style="color: gray; font-size: small">状态：</div>
            <div style="margin: 10px 0; font-size: medium">
              <dict-tag :options="dict.type.task_status" :value="task.status"/>
            </div>
          </el-card>
        </div>
        <van-empty
          description="暂无数据"
          v-if="taskList.length === 0 && !loading"
        />
      </van-list>
      <el-button
        type="primary"
        icon="el-icon-edit"
        circle
        class="submitButton"
        @click="toTargetAddOrUpdate('-1')"
      ></el-button>

    <van-popup
      v-model="show"
      round
      position="bottom"
      :style="{ height: '80%' }"
      closeable
      close-icon="close"
    >
    <h3 style="text-align: center">设置工单完成情况</h3>
      <van-form @submit="submitForm" style="margin-top: 30px">
        <van-field
          v-model="form.startTime"
          label="开始日期"
          placeholder="请选择开始日期"
          @click="startTimeFlag = true"
          :rules="[{ required: true, message: '开始日期不能为空' }]"
        />
        <van-calendar
          v-model="startTimeFlag"
          @confirm="onConfirmDate($event, 'startTimeFlag', 'startTime')"
        />
        <van-field
          v-model="form.endTime"
          label="开始日期"
          placeholder="请选择开始日期"
          @click="endTimeFlag = true"
          :rules="[{ required: true, message: '开始日期不能为空' }]"
        />
        <van-calendar
          v-model="endTimeFlag"
          @confirm="onConfirmDate($event, 'endTimeFlag', 'endTime')"
        />
        <van-field
          v-model="form.actualDay"
          type="number"
          label="实际天数"
          placeholder="请输入实际天数"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >确定</van-button
          >
        </div>
      </van-form>
    </van-popup>
    </div>
  </div>
</template>
  <script>
import { listTask, delTask, getTask, accomplishTaskInfo  } from "@/api/crm/task";
export default {
  name: "taskListMobile",
  dicts: ["task_type", "task_level", "task_mode", "task_status"],
  components: {},
  props: {
    userList: {
      type: Array,
      default: [],
    },

    customerList: {
      type: Array,
      default: [],
    },
    orderListAll: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      yearShow: false,
      showPicker: false,
      // 遮罩层
      loading: false,
      finished: false,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        year: null,
        targetType: null,
        createBy: null,
      },
      dictList: [],
      taskList: [],
      colorFlag: false,
      flag: false,
      show: false,
      startTimeFlag: false,
      endTimeFlag: false,
      form: {}
    };
  },
  created() {},
  methods: {
    submitForm(){
      accomplishTaskInfo(this.form).then((response) => {
        this.$toast.success("修改成功");
        this.show = false;
        this.handleQuery();
      });
    },
    /** 完成按钮 */
    accomplish(id) {
      getTask(id).then((response) => {
        this.form = response.data;
        this.show = true
      });
    },
    onConfirmDate(date, flag, fildes) {
      this[flag] = false;
      this.form[fildes] = `${date.getFullYear()}-${
        date.getMonth() + 1
      }-${date.getDate()}`;
    },
    onSelect(action, id) {
      if (action.text === "修改") {
        this.$router.push("/crm/task/" + id);
      } else if (action.text === "删除") {
        this.handleDelete(id);
      } else if (action.text === "详情") {
        this.$router.push("/crm/task/" + id);
      } else if (action.text === "完成") {
        this.accomplish(id)
      }
    },
    /** 删除按钮操作 */
    handleDelete(id) {
      this.$dialog
        .confirm({
          title: "工单删除提醒",
          message: "提交后将无法修改, 是否继续?",
        })
        .then(() => {
          delTask(id).then((res) => {
            this.$toast.success("删除成功");
            this.handleQuery();
          });
        });
    },
    toTargetAddOrUpdate(id) {
      this.$router.push("/crm/task/" + id);
    },
    popupClose() {
      if (
        this.queryParams.taskType ||
        this.queryParams.userId ||
        this.queryParams.customerId || 
        this.queryParams.orderId || 
        this.queryParams.createBy
      ) {
        this.colorFlag = true;
      } else {
        this.colorFlag = false;
      }
    },

    onConfirm(time) {
      this.queryParams.year = time;
      this.yearShow = false;
    },

    /** 查询工单列表 */
    async getList() {
      this.loading = true;
      try {
        let obj = JSON.parse(JSON.stringify(this.queryParams));
        let res = await listTask(obj);
        // 判断是否加载完所有数据
        if (this.taskList.length >= res.total) {
          this.finished = true;
        } else {
          this.taskList.push(
            ...res.rows.map((item) => {
              const actions = [];
              if (item.status === "1") {
                actions.unshift({ text: "删除", icon: "delete-o" });
                actions.unshift({ text: "详情", icon: "apps-o" });
              } else if (item.status === "0") {
                actions.unshift({ text: "删除", icon: "delete-o" });
                actions.unshift({ text: "修改", icon: "edit" });
                actions.unshift({ text: "完成", icon: "success" });
              }
              return {
                ...item,
                flag: false,
                actions,
              };
            })
          );
          this.queryParams.pageNum += 1;
        }
      } catch (error) {
        console.error("加载数据失败", error);
      } finally {
        this.loading = false;
      }
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        year: null,
        targetType: null,
        createBy: null,
      };
      this.handleQuery();
      this.colorFlag = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.taskList = [];
      this.queryParams.pageNum = 1;
      this.showPicker = false;
      this.getList();
    },
  },
};
</script>
  
  <style scoped>
.modal-content {
  display: table;
  width: 100%;
  height: 100%;
}

.modal-body {
  display: table-row;
  height: 100%;
}

.modal-footer {
  display: table-row;
  text-align: center;
  padding: 16px;
  background-color: white;
  display: flex;
  justify-content: space-around;
  border-top: 1px solid #e4dfdf;
}

.modal-footer button {
  width: 45%;
  border-radius: 10px;
}

.submitButton {
  position: fixed;
  top: 85%;
  left: 85%;
}
</style>